package com.cameron.serviceedu.controller.front;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cameron.serviceedu.client.UserCenterClient;
import com.cameron.serviceedu.entity.*;
import com.cameron.serviceedu.service.EduCommentService;
import com.cameron.serviceedu.service.EduCourseService;
import com.cameron.utils.Result;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author cameron
 * @since 2022-07-14
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/service/edu-comment")
@CrossOrigin
public class EduCommentController {
    private final EduCommentService commentService;
    private final EduCourseService courseService;
    private final UserCenterClient userCenterClient;

    //评论分页查询
    @GetMapping("getAllComment/{currentPage}/{pageSize}")
    public Result page(@PathVariable int currentPage, @PathVariable int pageSize){
        Page<EduComment> page = new Page<>(currentPage,pageSize);
        commentService.page(page,null);
        return Result.ok().data("records",page.getRecords()).data("total",page.getTotal());
    }

    @PostMapping("addComment/{courseId}")
    public Result addComment(@PathVariable String courseId, @RequestBody String comment,
                             HttpServletRequest request){
        if(StringUtils.isAnyBlank(comment,courseId)){
            return Result.error();
        }
        EduComment eduComment = new EduComment();
        eduComment.setContent(comment);

        try {
            //1.远程调用userCenter模块中的查询用户信息方法。
            UcenterMember userInfo = (UcenterMember) userCenterClient.getInfo(request).getData().get("userInfo");
            if (userInfo == null){
                return Result.error().message("请先登录！");
            }
            //3.将用户信息封装到comment对象中。
            eduComment.setMemberId(userInfo.getId());
            eduComment.setAvatar(userInfo.getAvatar());
            eduComment.setNickname(userInfo.getNickname());
        }catch (Exception e){
            e.printStackTrace();
        }
        //2.查询讲师id
        EduCourse course = courseService.getById(courseId);
        if (course == null) {
            return Result.error().message("该课程不存在或已被删除！");
        }
        eduComment.setCourseId(courseId);
        eduComment.setTeacherId(course.getTeacherId());

/*        //2.远程调用userCenter模块中的查询用户信息方法。
        UcenterMember userInfo = (UcenterMember) userCenterClient.getInfo(request).getData().get("userInfo");
        //3.将用户信息封装到comment对象中。
        eduComment.setMemberId(userInfo.getId());
        eduComment.setAvatar(userInfo.getAvatar());
        eduComment.setNickname(userInfo.getNickname());*/
        //4.将comment对象添加到数据库中
        return commentService.save(eduComment) ? Result.ok() : Result.error().message("评论失败");
    }


}

